package com.youli.gb.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import com.youli.gb.constant.SysConstatnt;
import com.youli.gb.model.SysRole;
import com.youli.gb.model.SysUser;
import com.youli.gb.service.ISysRoleService;
import com.youli.gb.service.ISysUserService;
import com.youli.gb.service.impl.SysRoleServiceImpl;
import com.youli.gb.service.impl.SysUserServiceImpl;

import cn.hutool.crypto.SecureUtil;

@WebServlet("/user.do")
public class SysUserServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;	
	
	//注入userService
	private ISysUserService userService = new SysUserServiceImpl();	
	//注入roleService   
	private ISysRoleService roleService = new SysRoleServiceImpl();
	
    public SysUserServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String type = request.getParameter("type");
		
		if (type.equals("list")) {
			list(request, response);
		}else if(type.equals("add")) {
			add(request, response);			
		}else if(type.equals("delete")) {
			delete(request, response);
		}else if(type.equals("deleteByIds")) {
			deleteByIds(request, response);
		}else if(type.equals("get")) {
			get(request, response);
		}else if(type.equals("edit")) {
			edit(request, response);
		}else if(type.equals("toAdd")) {
			toAdd(request, response);
		}else if (type.equals("login")) {
			login(request, response);
		}else if (type.equals("logout")) {
			logout(request, response);
		}else if (type.equals("modifyPassword")) {
			modifyPassword(request, response);
		}else {
			int id = Integer.valueOf(request.getParameter("id"));
			int ret = this.userService.modifyPassword(SecureUtil.md5(SysConstatnt.DEFAULT_PASSWORD),id);
			if (ret >0) {
				request.setAttribute("msg", "重置密码成功！");
			} else {
				request.setAttribute("msg", "重置密码失败！");
			}
			request.getRequestDispatcher("/user.do?type=list").forward(request, response);
		}
	}

	private void modifyPassword(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取数据
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		String newPassword2 = request.getParameter("newPassword2");
		HttpSession session =request.getSession();
		SysUser loginUser = (SysUser) session.getAttribute(SysConstatnt.SESSION_USER);
		
		//验证
		if (!SecureUtil.md5(oldPassword).equals(loginUser.getPassword())) {
			request.setAttribute("msg", "旧密码错误！");
			request.getRequestDispatcher("user/modifypassword.jsp").forward(request, response);
		}
		if (SecureUtil.md5(newPassword).equals(loginUser.getPassword())) {
			request.setAttribute("msg", "新密码与旧密码一致！");
			request.getRequestDispatcher("user/modifypassword.jsp").forward(request, response);
		}
		if (!newPassword.equals(newPassword2)) {
			request.setAttribute("msg", "新密码与确认密码不一致！");
			request.getRequestDispatcher("user/modifypassword.jsp").forward(request, response);
		}
		if (StringUtils.isNoneBlank(oldPassword) && StringUtils.isNoneBlank(newPassword2) && StringUtils.isNoneBlank(newPassword)) {
			int ret = this.userService.modifyPassword(SecureUtil.md5(newPassword),loginUser.getId());
			if (ret >0) {
				request.getRequestDispatcher("/user.do?type=logout").forward(request, response);
			} else {
				request.setAttribute("msg", "修改密码失败！");
				request.getRequestDispatcher("user/modifypassword.jsp").forward(request, response);
			}
		}else {
			request.setAttribute("msg", "密码信息不能为空！");
			request.getRequestDispatcher("user/modifypassword.jsp").forward(request, response);
		}
	}

	private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session =request.getSession();
		session.removeAttribute(SysConstatnt.SESSION_USER);
		session.invalidate();
		//跳转主页
		response.sendRedirect(request.getContextPath() + "/message.do?type=list");
	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		
		if (StringUtils.isNoneBlank(account) && StringUtils.isNoneBlank(password)) {
			SysUser loginUser = this.userService.login(account,SecureUtil.md5(password));
			if (loginUser != null) {
				//数据保存在会话域中
				HttpSession session =request.getSession();
				session.setAttribute(SysConstatnt.SESSION_USER, loginUser);
			} else {
				request.setAttribute("msg", "账号或密码错误！");
			}
		}else {
			request.setAttribute("msg", "错误，账号或密码为空！");
		}
		
		//登录成功与否均跳转到主页
		request.getRequestDispatcher("/message.do?type=list").forward(request, response);
	}

	private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<SysRole> roles = this.roleService.getAll();
		request.setAttribute("roles",roles);
		request.getRequestDispatcher("user/adduser.jsp").forward(request, response);
	}

	private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取参数
		int id = Integer.valueOf(request.getParameter("id"));
		String loginName = request.getParameter("loginName");
		String gender = request.getParameter("gender");
		String realName = request.getParameter("realName");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		int roleId = Integer.valueOf(request.getParameter("roleId"));
		
		
		SysRole role = this.roleService.getById(roleId);
		
		//保存修改
		SysUser sysUser = new SysUser(id,loginName, SecureUtil.md5(SysConstatnt.DEFAULT_PASSWORD), realName, gender, email, phone,role);
		int ret = this.userService.edit(sysUser);
		if(ret > 0) {
			request.setAttribute("msg", "修改成功！");
		}else {
			request.setAttribute("msg", "修改失败！");
		}
		request.getRequestDispatcher("user/userresult.jsp").forward(request, response);
	}

	private void get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		SysUser sysUser = this.userService.getById(Integer.valueOf(id));
		request.setAttribute("user", sysUser);
		List<SysRole> roles = this.roleService.getAll();
		request.setAttribute("roles",roles);
		request.getRequestDispatcher("user/edituser.jsp").forward(request, response);
	}

	private void deleteByIds(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String ids = request.getParameter("ids");//1,2,3,4,5
		String[] idArr = ids.split(",");
		int ret = this.userService.deleteByIds(idArr);
		if(ret > 0) {
			request.setAttribute("msg", "删除成功！");
		}else {
			request.setAttribute("msg", "删除失败！");
		}
		request.getRequestDispatcher("user/userresult.jsp").forward(request, response);
	}

	private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		int ret = this.userService.deleteById(Integer.valueOf(id));
		if(ret > 0) {
			request.setAttribute("msg", "删除成功！");
		}else {
			request.setAttribute("msg", "删除失败！");
		}
		request.getRequestDispatcher("user/userresult.jsp").forward(request, response);
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取参数
		String loginName = request.getParameter("loginName");
		String gender = request.getParameter("gender");
		String realName = request.getParameter("realName");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		int roleId = Integer.valueOf(request.getParameter("roleId"));
		//唯一性检查
		SysUser loginUser = this.userService.getByLoginName(loginName);
		SysUser emailUser = this.userService.getByEmail(email);
		SysUser phoneUser = this.userService.getByPhone(phone);
		if(loginUser != null) {
			request.setAttribute("msg", "登录名称重复，请更换！");
			request.getRequestDispatcher("user/adduser.jsp").forward(request, response);
		}
		if(emailUser != null) {
			request.setAttribute("msg", "电子邮箱重复，请更换！");
			request.getRequestDispatcher("user/adduser.jsp").forward(request, response);
		}
		if(phoneUser != null) {
			request.setAttribute("msg", "电话号码重复，请更换！");
			request.getRequestDispatcher("user/adduser.jsp").forward(request, response);
		}
		if (loginUser == null && emailUser == null && phoneUser == null) {
			//添加
			SysRole role = this.roleService.getById(roleId);
			SysUser sysUser = new SysUser(loginName, SecureUtil.md5(SysConstatnt.DEFAULT_PASSWORD), realName, gender, email, phone,role);
			int ret = this.userService.add(sysUser);
			if(ret > 0) {
				request.setAttribute("msg", "添加成功！");
			}else {
				request.setAttribute("msg", "添加失败！");
			}
			request.getRequestDispatcher("user/userresult.jsp").forward(request, response);
		}
	}
	
	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//从service中获取所有角色信息
		List<SysUser> users = userService.getAll();
		request.setAttribute("users", users);
		request.getRequestDispatcher("user/users.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}




















